<script lang="ts">
import { api } from '@/api/api';
import { DownOutlined, FileTextOutlined, LinkOutlined, RightOutlined, VideoCameraOutlined } from '@ant-design/icons-vue';
import { Button, message } from 'ant-design-vue';
import axios from 'axios';
import { defineComponent, onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router'; // 引入 useRoute
interface SourceFile {
  courseFileId: string;
  sourceId: string;
  name: string;
  sourcePath: string | null;
  createdAt: string;
  courseId: string | null;
  tag: string;
  ossWriteStatus: boolean;
  transcriptionComplete: boolean;
  ragCompleteStatus: boolean;
  smartTextStatus: boolean;
  transcriptionCompleteStatus: boolean;
  handleCompleteStatus: boolean;
  web: string | null;
  sortOrder: number | null;
}

interface WebSource {
  webName: string;
  web: string;
}

interface CourseFile {
  courseFileId: string;
  name: string | null;
  parentId: string | null;
  filePath: string | null;
  createdAt: string | null;
  childId: string | null;
  tag: string | null;
  level: number;
  courseId: string | null;
  sortOrder: number | null;
  courseImageUrl: string | null;
  ossWriteStatus: boolean | null;
  transcriptionComplete: boolean | null;
  ragCompleteStatus: boolean | null;
  smartTextStatus: boolean | null;
  transcriptionCompleteStatus: boolean | null;
  handleCompleteStatus: boolean | null;
  web: string | null;
  childFiles: CourseFile[];
  sourceFiles: SourceFile[];
  webSourses: WebSource[];
}

export default defineComponent({
  name: 'CourseDesc',
  components: {
    DownOutlined,
    RightOutlined,
    FileTextOutlined,
    VideoCameraOutlined,
    LinkOutlined,
    AButton: Button,
  },
  setup() {
    const expandedChapters = ref<string[]>([]);
    const expandedSections = ref<string[]>([]);
    const scheduleData = ref<CourseFile[]>([]);

    const router = useRouter();
    const route = useRoute(); // 获取当前路由

    // 获取cookie值的辅助函数
    const getCookieValue = (name: string): string | null => {
      const match = document.cookie.match(new RegExp(`(^| )${name}=([^;]+)`));
      return match ? decodeURIComponent(match[2]) : null;
    };

    // 获取课程文件
    const fetchCourseFiles = async () => {
      const folderId = route.params.folderId as string; // 从路由的路径参数中获取 folderId
      const courseId = route.params.courseId as string; // 从路由的路径参数中获取 courseId
      const accessToken = getCookieValue('access_token_lf'); // 获取 cookie 中的 token
      localStorage.setItem('courseId', courseId);
      localStorage.setItem('folderId', folderId);
      // 打印调试信息
      // console.log('Fetching courseId:', courseId);
      // console.log('Fetching accessToken:', accessToken);
      // console.log('Fetching folderId:', folderId);

      if (!folderId || !courseId || !accessToken) {
        console.error('缺少必要的参数: folderId, courseId 或 accessToken');
        return;
      }

      try {
        const response = await axios.get('/java/teacher/StudySpaceTeacher/getAllCourses', {
          headers: { Authorization: `Bearer ${accessToken}` },
          params: { courseFileId: folderId },
        });

        // console.log('Fetch Course Files Response:', response.data); // 调试信息

        if (response.status === 200 && response.data && response.data.code === 200) {
          const childFiles: CourseFile[] = response.data.data?.childFiles;

          if (Array.isArray(childFiles)) {
            scheduleData.value = childFiles;
            expandedChapters.value = childFiles.map((file: CourseFile) => file.courseFileId);
          }
          else {
            console.error('childFiles 不是数组或未定义:', childFiles);
            scheduleData.value = [];
            expandedChapters.value = [];
          }
        }
        else {
          console.error('响应结构不符合预期:', response.data);
        }
      }
      catch (error) {
        console.error('获取课程文件时出错:', error);
      }
    };

    onMounted(fetchCourseFiles);

    // 切换章节的展开状态
    const toggleChapter = (courseFileId: string) => {
      if (expandedChapters.value.includes(courseFileId))
        expandedChapters.value = expandedChapters.value.filter(id => id !== courseFileId);
      else
        expandedChapters.value.push(courseFileId);
    };

    // 切换小节的展开状态
    const toggleSection = (courseFileId: string) => {
      if (expandedSections.value.includes(courseFileId))
        expandedSections.value = expandedSections.value.filter(id => id !== courseFileId);
      else
        expandedSections.value.push(courseFileId);
    };

    // 通用资源点击处理函数

    // 文档点击处理
    const handleDocumentClick = async (file: SourceFile | CourseFile) => {
      const sourceId = 'sourceId' in file ? file.sourceId : file.courseFileId;
      const accessToken = getCookieValue('access_token_lf');
      const courseId = route.params.courseId as string | undefined; // 从路由获取 courseId
      const folderId = route.params.folderId as string | undefined; // 从路由获取 folderId
      const filePath = 'sourcePath' in file ? file.sourcePath : undefined;
      if (!sourceId || !courseId || !folderId || !accessToken)
        return;

      // 跳转路由到 /learn/document/:courseId/:folderId/:sourceId
      router.push({ name: 'DocumentViewer', params: { courseId, folderId, sourceId, filePath } });

      // // 存储 sourceId 到 localStorage
      // localStorage.setItem('sourceId', sourceId);
      // selectedSourceStore.setSelectedSourceId(sourceId);
      // try {
      //   const response = await axios.get('/java/ground/study/course/get_source_url', {
      //     headers: { Authorization: `Bearer ${accessToken}` },
      //     params: { sourceId },
      //   });

      //   // console.log('Document URL Response:', response.data); // 调试信息

      //   const fileUrl = response.data.data;
      //   if (fileUrl) {
      //     localStorage.setItem('pdfUrl', fileUrl);
      //     router.push({ path: '/learn/document' });
      //   }
      //   else {
      //     console.error('获取文件URL失败');
      //     message.error('获取文件URL失败');
      //   }
      // }
      // catch (error) {
      //   console.error('请求失败:', error);
      //   message.error('请求失败');
      // }
    };

    // 音视频点击处理
    const handleVideoClick = async (file: SourceFile | CourseFile) => {
      const sourceId = 'sourceId' in file ? file.sourceId : file.courseFileId;
      const accessToken = getCookieValue('access_token_lf');
      const courseId = route.params.courseId as string | undefined; // 从路由获取 courseId
      const folderId = route.params.folderId as string | undefined; // 从路由获取 folderId

      if (!sourceId || !courseId || !folderId || !accessToken)
        return;
      const filePath = 'sourcePath' in file ? file.sourcePath : undefined;
      // 跳转路由到 /learn/document/:courseId/:folderId/:sourceId
      router.push({ name: 'video', params: { courseId, folderId, sourceId, filePath } });
      // const sourceId = 'sourceId' in file ? file.sourceId : file.courseFileId;
      // const accessToken = getCookieValue('access_token_lf');
      // const courseId = route.params.courseId as string | undefined; // 从路由获取 courseId

      // if (!sourceId || !courseId || !accessToken)
      //   return;

      // // 存储 sourceId 到 localStorage
      // localStorage.setItem('sourceId', sourceId);

      // selectedSourceStore.setSelectedSourceId(sourceId);

      // try {
      //   const transResponse = await axios.get('/java/teacher/StudySpaceTeacher/getSourceTransResult', {
      //     headers: { Authorization: `Bearer ${accessToken}` },
      //     params: { courseSourceId: sourceId },
      //   });

      //   fileTransStore.setData(transResponse.data);

      //   const videoResponse = await axios.get('/java/ground/study/course/get_source_url', {
      //     headers: { Authorization: `Bearer ${accessToken}` },
      //     params: { sourceId },
      //   });

      //   // console.log('Video URL Response:', videoResponse.data); // 调试信息

      //   const videoUrl = videoResponse.data.data;
      //   if (videoUrl) {
      //     localStorage.setItem('videoUrl', videoUrl);
      //     router.push({ path: '/learn/video' });
      //   }
      //   else {
      //     console.error('获取视频URL失败');
      //     message.error('获取视频URL失败');
      //   }
      // }
      // catch (error) {
      //   console.error('请求失败:', error);
      //   message.error('请求失败');
      // }
    };

    // 处理其他资源点击
    const handleResourceClickSpecific = async (file: SourceFile | CourseFile) => {
      const sourcePath = 'sourcePath' in file ? file.sourcePath : file.filePath;
      if (sourcePath) {
        // 假设资源可以通过 sourcePath 构建链接
        const resourceUrl = `/path/to/resource/${sourcePath}`; // 根据实际情况修改
        window.open(resourceUrl, '_blank');
      }
      else {
        console.error('资源路径为空');
        message.error('资源路径为空');
      }
    };

    // 处理网页资源点击
    const handleWebClick = async (file: SourceFile | CourseFile) => {
      const sourceId = 'sourceId' in file ? file.sourceId : file.courseFileId; // 获取sourceId

      if (!sourceId) {
        console.error('未提供 sourceId');
        message.error('未提供 sourceId');
        return;
      }

      try {
        // 调用接口获取资源 URL
        const response = await api.get('/java/ground/study/course/get_source_url', {
          params: { sourceId },
        });

        if (response) {
          const fileUrl = response.data; // 获取返回的 URL
          if (fileUrl) {
            window.open(fileUrl, '_blank'); // 在新窗口中打开链接
          }
          else {
            console.error('获取文件URL失败');
            message.error('获取文件URL失败');
          }
        }
        else {
          console.error('请求失败，状态码不为200');
          message.error('请求失败');
        }
      }
      catch (error) {
        console.error('请求失败:', error);
        message.error('请求失败');
      }
    };

    // 处理Bilibili按钮点击
    const handleThirdButtonClick = (webUrl: string) => {
      if (webUrl)
        window.open(webUrl, '_blank');
      else
        console.error('未提供webUrl');
    };

    // 获取顶级资源（即没有 parentId 的资源）
    const getTopLevelResources = (files: CourseFile[]): CourseFile[] => {
      return files.filter(file => !file.parentId && (file.tag === '资源' || file.tag === '文档' || file.tag === '音视频' || file.tag === '网页资源'));
    };

    const handleResourceClick = async (file: SourceFile | CourseFile) => {
      if (file.tag === '文档')
        await handleDocumentClick(file);
      else if (file.tag === '音视频')
        await handleVideoClick(file);
      else if (file.tag === '资源')
        await handleResourceClickSpecific(file);
      else if (file.tag === '网页资源')
        handleWebClick(file);
    };

    return {
      expandedChapters,
      expandedSections,
      scheduleData,
      toggleChapter,
      toggleSection,
      handleResourceClick,
      handleThirdButtonClick,
      getTopLevelResources,
      DownOutlined,
      RightOutlined,
      FileTextOutlined,
      VideoCameraOutlined,
      LinkOutlined,
    };
  },
});
</script>

<template>
  <div class="tabs">
    <!-- 课程目录部分 -->
    <div class="shedule bg-white">
      <ul>
        <!-- 循环渲染每个章节 -->
        <li v-for="chapter in scheduleData" :key="chapter.courseFileId" class="chapter-item">
          <div class="chapterHeader" @click="toggleChapter(chapter.courseFileId)">
            <AButton type="text" class="expandButton">
              <!-- 根据是否展开显示不同的图标 -->
              <component :is="expandedChapters.includes(chapter.courseFileId) ? DownOutlined : RightOutlined" />
            </AButton>
            <span>{{ chapter.name || '无名称' }}</span>
          </div>

          <!-- 如果章节展开，显示其子文件（小节） -->
          <ul v-if="expandedChapters.includes(chapter.courseFileId)" class="sectionList">
            <li v-for="section in chapter.childFiles" :key="section.courseFileId" class="section-item">
              <div class="sectionHeader" @click="toggleSection(section.courseFileId)">
                <AButton type="text" class="expandButton">
                  <component :is="expandedSections.includes(section.courseFileId) ? DownOutlined : RightOutlined" />
                </AButton>
                <span>{{ section.name || '无名称' }}</span>
              </div>

              <!-- 如果小节展开，显示其资源 -->
              <div v-if="expandedSections.includes(section.courseFileId)" class="resources">
                <ul>
                  <!-- 渲染文档和音视频资源 -->
                  <li
                    v-for="sourceFile in section.sourceFiles"
                    :key="sourceFile.sourceId || sourceFile.courseFileId"
                    class="resourceItem clickable"
                    @click="handleResourceClick(sourceFile)"
                  >
                    <span>{{ sourceFile.name || '无名称' }}</span>
                    <div class="iconContainer">
                      <!-- 文档 -->
                      <FileTextOutlined v-if="sourceFile.tag === '文档'" />
                      <!-- 音视频 -->
                      <VideoCameraOutlined v-if="sourceFile.tag === '音视频'" />
                      <!-- 其他资源 -->
                      <FileTextOutlined v-if="sourceFile.tag === '资源'" /> <!-- 根据需要更换图标 -->
                      <!-- 网页资源 -->
                      <LinkOutlined v-if="sourceFile.tag === '网页资源'" />
                    </div>
                  </li>

                  <!-- 渲染Bilibili链接 -->
                  <li
                    v-for="webSource in section.webSourses"
                    :key="webSource.webName"
                    class="resourceItem clickable"
                    @click="handleThirdButtonClick(webSource.web)"
                  >
                    <span>{{ webSource.webName }}</span>
                    <div class="iconContainer">
                      <LinkOutlined />
                    </div>
                  </li>
                </ul>
              </div>
            </li>
          </ul>

          <!-- 如果章节下有直接的资源（非子文件），直接渲染 -->
          <div v-if="chapter.sourceFiles.length > 0 || chapter.webSourses.length > 0" class="resources">
            <ul>
              <li
                v-for="sourceFile in chapter.sourceFiles"
                :key="sourceFile.sourceId || sourceFile.courseFileId"
                class="resourceItem clickable"
                @click="handleResourceClick(sourceFile)"
              >
                <span>{{ sourceFile.name || '无名称' }}</span>
                <div class="iconContainer">
                  <!-- 文档 -->
                  <FileTextOutlined v-if="sourceFile.tag === '文档'" />
                  <!-- 音视频 -->
                  <VideoCameraOutlined v-if="sourceFile.tag === '音视频'" />
                  <!-- 其他资源 -->
                  <FileTextOutlined v-if="sourceFile.tag === '资源'" /> <!-- 根据需要更换图标 -->
                  <!-- 网页资源 -->
                  <LinkOutlined v-if="sourceFile.tag === '网页资源' && sourceFile.web" />
                </div>
              </li>
              <li
                v-for="webSource in chapter.webSourses"
                :key="webSource.webName"
                class="resourceItem clickable"
                @click="handleThirdButtonClick(webSource.web)"
              >
                <span>{{ webSource.webName }}</span>
                <div class="iconContainer">
                  <LinkOutlined />
                </div>
              </li>
            </ul>
          </div>

          <hr class="divider">
        </li>

        <!-- @ts-ignore -->
        <li
          v-for="resource in getTopLevelResources(scheduleData)"
          :key="(resource as unknown as SourceFile).sourceId || resource.courseFileId"
          class="resourceItem clickable"
          @click="handleResourceClick(resource)"
        >
          <span>{{ resource.name || '无名称' }}</span>
          <div class="iconContainer">
            <!-- 文档 -->
            <FileTextOutlined v-if="resource.tag === '文档'" />
            <!-- 音视频 -->
            <VideoCameraOutlined v-if="resource.tag === '音视频'" />
            <!-- 其他资源 -->
            <FileTextOutlined v-if="resource.tag === '资源'" /> <!-- 根据需要更换图标 -->
            <!-- 网页资源 -->
            <LinkOutlined v-if="resource.tag === '网页资源' && resource.web" />
          </div>
        </li>
      </ul>
    </div>
  </div>
</template>

<style scoped lang="scss">
.clickable {
  cursor: pointer;
}

.tabs {
  display: flex;
  flex-direction: column;
  gap: 24px;
  overflow: auto;

  .tabTitle {
    font-size: 1.75em;
    font-weight: 800;
    margin-bottom: 0.5em;
    display: inline-block;
  }

  .cardWrapper {
    padding: 14px 14px 0 14px;
    font-size: 16px;
    line-height: 1.7;

    br {
      margin-top: 12px;
    }

    .card {
      margin-bottom: 1em;
      width: 32%;
      border-radius: 1.25em;
      background-color: rgba(255, 255, 255, 1);
      border: 0.06em solid rgba(187, 187, 187, 1);
      padding: 1em;
      box-sizing: border-box;

      .cardTop {
        display: flex;
        align-items: center;

        .show {
          height: 4em;
          display: flex;
          justify-content: space-between;
          flex-direction: column;
          margin-left: 1em;

          .topTags {
            padding: 0 0.5em;
            border: 1px solid #b7b9b688;
            border-radius: 0.25em;
            background-color: rgba(255, 255, 255, 1);
            color: rgba(16, 16, 16, 1);
            font-size: 1em;
            text-align: center;
            font-family: Roboto;
          }
        }
      }
    }
  }

  .table {
    width: 100%;
    border-collapse: collapse;

    td,
    th {
      border: 1px solid #ddd;
      padding: 8px;
      text-align: left;
    }

    tr:nth-child(even) {
      background-color: #f2f2f2;
    }

    th {
      background-color: #f1f1f1;
      font-weight: bold;
    }
  }

  .personDesc {
    display: flex;
    align-items: center;
    gap: 12px;

    & > div:nth-child(1) {
      width: 100px;
      height: 100px;

      & > img {
        height: 100%;
        width: 100%;
        border-radius: 50%;
      }
    }

    & > div:nth-child(2) {
      p {
        line-height: 1;
      }

      & > p:nth-child(1) {
        color: #63c1ff;
      }
    }
  }

  .shedule {
    list-style-type: none;
    padding: 12px;
    margin: 0;
    border-radius: 8px;
    border: 1px solid rgba(0, 0, 0, 0.08);
    box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.08);

    & > li {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      margin-bottom: 10px;
      border-bottom: 1px solid rgba(0, 0, 0, 0.08);

      span {
        margin-right: 10px;
        font-size: 18px;
        line-height: 2.2;
      }

      & > ul {
        width: 100%;
        list-style-type: none;
        padding-left: 40px;

        li {
          display: flex;
          justify-content: space-between;
          width: 100%;
          margin-bottom: 5px;

          .btn {
            display: inline-block;
            background-color: #009c7b;
            color: #fff;
            padding: 1px 4px;
            border-radius: 4px;
          }

          span {
            font-size: 16px;
            line-height: 2.0;
          }

          & > div {
            display: flex;
            justify-content: flex-end;
            gap: 20px; /* 增加图标之间的间距 */
            padding-right: 30px; /* 增加图标与右边框之间的间距 */

            a {
              display: flex;
              align-items: center;
              justify-content: center;
              width: 24px; /* 图标的固定宽度 */
              height: 24px; /* 图标的固定高度 */
              text-align: center;
            }
          }
        }
      }
    }
  }

  .subTtitle {
    font-size: 16px;
  }

  .activeText {
    color: #63c1ff;
  }

  .cardBox {
    box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.08);
    border-radius: 8px;
    border: 1px solid rgba(0, 0, 0, 0.08);
  }

  .imgWrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .chapterHeader, .sectionHeader {
    display: flex;
    align-items: center;
    cursor: pointer;
  }

  .expandButton {
    margin-right: 8px;
  }

  .sectionList, .resourceList {
    list-style: none;
    padding-left: 20px;
  }

  .resourceItem {
    display: flex;
    align-items: center;
    margin-bottom: 5px;
  }

  .iconContainer a {
    margin-left: 8px;
    color: inherit;
  }

  .divider {
    border: none;
    border-top: 1px solid #e8e8e8;
    margin: 10px 0;
  }
}
</style>
